<template>
    <a-form layout="vertical">
        <a-form-item label="用户名" name="username" v-bind="validateInfos.username">
            <a-input v-model:value="form.username" placeholder="请输入用户名" :maxlength="68" size="large">
                <template #prefix>
                    <ant-icon-user-outlined />
                </template>
            </a-input>
        </a-form-item>

        <a-form-item label="密码" name="password" v-bind="validateInfos.password">
            <a-input-password v-model:value="form.password" placeholder="请输入密码" size="large">
                <template #prefix>
                    <ant-icon-lock-outlined />
                </template>
            </a-input-password>
        </a-form-item>

        <a-form-item label="验证码" name="captcha" v-bind="validateInfos.captcha">
            <a-input-group>
                <a-row :gutter="8">
                    <a-col :span="18">
                        <a-input v-model:value="form.captcha" placeholder="请输入验证码" :maxlength="4" size="large">
                            <template #prefix>
                                <ant-icon-wallet-outlined />
                            </template>
                        </a-input>
                    </a-col>
                    <a-col :span="4" :offset="1">
                        <figure class="bulma-image" style="height: 100%;">
                            <img style="height: 100%;" :src="`data:image/png;base64,${captcha_img}`" alt="验证码" 
                                @click="getCaptchaImage">
                        </figure>
                    </a-col>
                </a-row>
            </a-input-group>
        </a-form-item>
        <a-form-item>
            <a-button type="primary" size="large" block @click="onSubmit">登录</a-button>
        </a-form-item>
    </a-form>
</template>

<script setup>
    import { ref, reactive, onMounted, toRaw, getCurrentInstance } from 'vue'
    import { useRouter } from 'vue-router'
    import { Form, message } from 'ant-design-vue';
    import { useTokenStore } from '@/stores/token';
    import { useMenusStore } from '@/stores/menus';

    const { proxy } = getCurrentInstance()
    const router = useRouter()
    const tokenStore = useTokenStore()
    const menusStore = useMenusStore()

    // 获取表单实例
    const useForm = Form.useForm
    // 验证码图片
    const captcha_img = ref("")
    // 表单数据
    const form = reactive({
        username: '',
        password: '',
        uid: '',
        captcha: ''
    })
    
    // 获取验证码图片
    const getCaptchaImage = async () => {
        const { data, isLoading } = await proxy.$api.captcha.getCaptchaCodeAPI()
        form.uid = data.value.uid
        captcha_img.value = data.value.image
    }

    // 初始化
    onMounted(() => {
       getCaptchaImage()
    })

    // 表单验证规则
    const rulesRef = reactive({
        username: [
            {
                required: true,
                message: '请输入用户名',
                trigger: 'blur'
            }
        ],
        password: [
            {
                required: true,
                message: '请输入密码',
                trigger: 'blur'
            }
        ],
        captcha: [
            {
                required: true,
                message: '请输入验证码',
                trigger: 'blur',
                validator: (rule, value) => {
                    if (value.length !== 4) {
                        return Promise.reject('验证码长度为4位')
                    }
                    return Promise.resolve()
                }
            }
        ]
    })

    // 表单验证
    const { resetFields, validate, validateInfos } = useForm(form, rulesRef, {
        onValidate: (...args) => console.log(...args),
    });

    // 登录点击事件
    const onSubmit = () => {
        validate().then(async () => {
            message.loading('登录中...', 1)
            const { data, isLoading } = await proxy.$api.system.LoginAPI(toRaw(form))
            tokenStore.setTokenRefresh(data.value.access, data.value.refresh)
            // 获取菜单
            if (tokenStore.isLogin) {
                const { data, isFinished } = await proxy.$api.system.getMenuAPI()
                menusStore.setMenus(data.value)
                const user = await proxy.$api.system.getUserInfoAPI()
                tokenStore.setUserInfo(user.data.value)
                router.push('/dashboard')
                message.success('登录成功')
            }
        })
    }
</script>